package com.liqin.nothing.client;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.mail.internet.MimeMessage;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class MailClient {

    private final JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    public void sendEmail(String to, String name, String city) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("李沁小迷弟" + " <" + from + ">");
            helper.setTo(to);
            helper.setSubject(name + "的今日份预报💗");
            helper.setText(getContent(city), true);
            javaMailSender.send(message);
            log.info("邮件发送成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String getContent(String city) {
        // 发送请求获取天气数据
        String weatherKey = "efbf95b61da53a74aa2f15bd1918a57d";
        String WeatherUrl = "http://apis.juhe.cn/simpleWeather/query";
        String LifeUrl = "http://apis.juhe.cn/simpleWeather/life";
        Map<String, String> params = new HashMap<>();
        params.put("key", weatherKey);
        params.put("city", city);
        String weatherJsonStr = getDataByHttp(WeatherUrl, params);
        String lifeIndexJsonStr = getDataByHttp(LifeUrl, params);

        // 发送请求获取彩虹屁
        String describeKey = "3dce266882ae1c902a925f80c47ceb07";
        String describeUrl = "https://apis.tianapi.com/caihongpi/index";
        params.clear();
        params.put("key", describeKey);
        String describe = getDataByHttp(describeUrl, params);
        JSONObject json = JSONObject.parseObject(describe);
        JSONObject result = json.getJSONObject("result");
        describe = result.getString("content");

        // 解析天气数据
        return generateEmailContent(weatherJsonStr, lifeIndexJsonStr, describe, city);

    }

    /**
     * 根据第三方接口获取数据
     *
     * @param baseUrl 接口地址
     * @param params 接口参数
     * @return json
     */
    private String getDataByHttp(String baseUrl, Map<String, String> params) {
        RestTemplate restTemplate = new RestTemplate();
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl);
        // 遍历 Map，动态添加所有查询参数
        params.forEach(builder::queryParam);
        URI uri = builder.encode(StandardCharsets.UTF_8)
                .build()
                .toUri();
        ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
        return response.getBody();
    }

    /**
     * 生成HTML格式邮件内容
     *
     * @param weatherJsonStr   天气数据
     * @param lifeIndexJsonStr 生活指数数据
     * @param describe         彩虹屁
     * @param city             城市
     * @return 邮件内容
     */
    public static String generateEmailContent(String weatherJsonStr, String lifeIndexJsonStr, String describe, String city) {
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>");
        html.append("<html lang=\"zh-CN\">");
        html.append("<head>");
        html.append("<meta charset=\"UTF-8\">");
        html.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
        html.append("<style>");
        html.append("body {");
        html.append("    font-family: Arial, sans-serif;");
        html.append("    margin: 0;");
        html.append("    padding: 15px;");
        html.append("    background-color: #f4f4f4;");
        html.append("}");
        html.append(".weather-container {");
        html.append("    background-color: #fff;");
        html.append("    border-radius: 10px;");
        html.append("    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);");
        html.append("    overflow: hidden;");
        html.append("}");
        html.append(".header {");
        html.append("    text-align: center;");
        html.append("    background-color: #007BFF;");
        html.append("    color: white;");
        html.append("    padding: 20px;");
        html.append("}");
        html.append(".realtime {");
        html.append("    flex-wrap: wrap;");
        html.append("    padding: 20px;");
        html.append("    border-bottom: 1px solid #eee;");
        html.append("    justify-content: space-around;");
        html.append("}");
        html.append(".realtime p {");
        html.append("    margin: 8px;");
        html.append("}");
        html.append(".life-index {");
        html.append("    padding: 20px;");
        html.append("    border-bottom: 1px solid #eee;");
        html.append("}");
        html.append(".life-index p {");
        html.append("    margin: 8px 0;");
        html.append("}");
        html.append(".forecast {");
        html.append("    padding: 20px;");
        html.append("}");
        html.append(".forecast table {");
        html.append("    width: 100%;");
        html.append("    border-collapse: collapse;");
        html.append("}");
        html.append(".forecast th, .forecast td {");
        html.append("    padding: 12px;");
        html.append("    text-align: left;");
        html.append("    border-bottom: 1px solid #eee;");
        html.append("}");
        html.append(".forecast th {");
        html.append("    background-color: #f9f9f9;");
        html.append("}");
        html.append("</style>");
        html.append("</head>");
        html.append("<body>");
        html.append("<div class=\"weather-container\">");
        html.append("<div class=\"header\">");
        html.append("<h1>").append(city).append("天气预报</h1>");
        html.append("<p>").append(describe).append("</p>");
        html.append("</div>");

        // 解析天气 JSON 数据
        JSONObject weatherJson = JSONObject.parseObject(weatherJsonStr);
        JSONObject weatherResult = weatherJson.getJSONObject("result");
        JSONObject realtime = weatherResult.getJSONObject("realtime");

        // 解析生活指数 JSON 数据
        JSONObject lifeIndexJson = JSONObject.parseObject(lifeIndexJsonStr);
        JSONObject lifeResult = lifeIndexJson.getJSONObject("result");
        JSONObject life = lifeResult.getJSONObject("life");

        html.append("<div class=\"realtime\">");
        html.append("<h2>实时天气</h2>");
        if (realtime != null) {
            html.append("<p>温度：").append(realtime.getString("temperature")).append("℃</p>");
            html.append("<p>天气状况：").append(realtime.getString("info")).append("</p>");
            html.append("<p>湿度：").append(realtime.getString("humidity")).append("%</p>");
            html.append("<p>风力：").append(realtime.getString("direct")).append(" ").append(realtime.getString("power")).append("</p>");
            html.append("<p>空气质量指数：").append(realtime.getString("aqi")).append("</p>");
        }
        html.append("</div>");

        html.append("<div class=\"life-index\">");
        html.append("<h2>生活指数</h2>");
        if (life != null) {
            String[] selectedIndices = {"shushidu", "chuanyi", "daisan"};
            for (String indexKey : selectedIndices) {
                JSONObject index = life.getJSONObject(indexKey);
                if (index != null) {
                    String indexName = getChineseName(indexKey);
                    html.append("<p>").append(indexName).append("：").append(index.getString("v")).append(" - ").append(index.getString("des")).append("</p>");
                }
            }
        }
        html.append("</div>");

        html.append("<div class=\"forecast\">");
        html.append("<h2>未来5天预报</h2>");
        html.append("<table>");
        html.append("<thead>");
        html.append("<tr>");
        html.append("<th>日期</th>");
        html.append("<th>天气</th>");
        html.append("<th>温度</th>");
        html.append("<th>风力风向</th>");
        html.append("</tr>");
        html.append("</thead>");
        html.append("<tbody>");
        JSONArray future = weatherResult.getJSONArray("future");
        Calendar calendar = Calendar.getInstance();
        for (int i = 0; i < future.size(); i++) {
            JSONObject day = future.getJSONObject(i);
            String dateStr;
            if (i == 0) {
                dateStr = "今天";
            } else if (i == 1) {
                dateStr = "明天";
            } else if (i == 2) {
                dateStr = "后天";
            } else {
                dateStr = day.getString("date").split("-")[2] + "日";
            }
            String weather = day.getString("weather");
            String temp = day.getString("temperature");
            String wind = day.getString("direct");
            html.append("<tr>");
            html.append("<td>").append(dateStr).append("</td>");
            html.append("<td>").append(weather).append("</td>");
            html.append("<td>").append(temp).append("</td>");
            html.append("<td>").append(wind).append("</td>");
            html.append("</tr>");
        }
        html.append("</tbody>");
        html.append("</table>");
        html.append("</div>");

        html.append("</div>");
        html.append("</body>");
        html.append("</html>");

        return html.toString();
    }

    private static String getChineseName(String key) {
        switch (key) {
            case "shushidu":
                return "舒适度";
            case "chuanyi":
                return "穿衣";
            case "daisan":
                return "带伞";
            default:
                return key;
        }
    }
}    